package cn.bxshey.systemLogInfo.listern;

import cn.bxshey.mq.constant.MQ;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @作者：不想说话而已
 * @Date：2023/12/6 21:18
 *
 * 配置 错误异常交换机
 *
 * 当消息重试达到一定次数的时候  将消息投递到异常处理的队列上
 */
@Component
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener.simple.retry",name = "enabled",havingValue = "true") //当配置文件某个属性为真的时候执行
public class ErrorMQConfig {

    //配置队列
    @Bean
    public Queue errorQueue(){
        return new Queue(MQ.QUEUE_ERROR);
    }

    //配置交换机
    @Bean
    public DirectExchange errorExchange(){
        return new DirectExchange(MQ.EXCHANGE_ERROR);
    }

    //启动时自动加载
    @Bean
    public Binding errorBinding(Queue errorQueue, DirectExchange errorExchange){
        return BindingBuilder.bind(errorQueue).to(errorExchange).with(MQ.KEY_ERROR);
    }

    //设置异常时的 交换机，匹配key
    @Bean
    public MessageRecoverer getMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate, MQ.EXCHANGE_ERROR,MQ.KEY_ERROR);
    }

}
